package com.bc.bcsellerapihttp.controller;

import com.bc.bcapi.service.T_ProjectService;
import com.bc.bcapi.service.T_User_seller_infoService;
import com.bc.bccore.common.LoginHelper;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bcmodel.BuyerUserInfo;
import com.bc.bcmodel.SellerUserInfo;
import com.bc.bcmodel.consts.GlobalSettings;
import com.bc.bcmodel.domain.T_User_seller_infoModel;
import com.bc.bcmodel.req.*;
import com.bc.bcmodel.resp.UserInviteResp;
import com.bc.bcsellerapihttp.common.UserContext;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.security.DES;
import com.bc.commoncore.util.CookieUtils;
import com.bc.commoncore.util.RandomCodeImgHelper;
import com.bc.commoncore.util.RandomCodeStrGenerator;
import com.bc.commoncore.util.StringUtils;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
//import java.io.OutputStream;

/**
 * @Name UserController
 * @Description
 * @Author douhaichao
 * @Date 2018/8/2 14:19
 * @Version 1.0
 **/
@RestController
@Api(value = "买家用户验证相关")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    T_User_seller_infoService t_User_seller_infoService;
    @Autowired
    T_ProjectService t_projectService;

    @ApiOperation(value = "用户邮箱验证{1.是否使用过;2.基本格式验证;}")
    @RequestMapping(value = "/nologon/marvel/checkemail", method = RequestMethod.GET)
    public JsonResult checkMail(UserEmailCheckReq req) {
        return t_User_seller_infoService.checkEmailUsed(req);
    }

    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/nologon/marvel/logon", method = RequestMethod.POST)
    public JsonResult logon(@RequestBody UserLogonReq req, HttpServletRequest request,
                            HttpServletResponse response) {
        return t_User_seller_infoService.logon(req, request, response);
    }

    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "/nologon/marvel/signup", method = RequestMethod.POST)
    public JsonResult signUp(@RequestBody UserSignUpReq req, HttpServletRequest request) {
        try {
            return t_User_seller_infoService.signUp(req, request);
        } catch (Exception e) {
            return new JsonResult(HttpReturnRnums.SystemError);
        }
    }

    @ApiOperation(value = "登录用户信息")
    @RequestMapping(value = "/marvel/userinfo", method = RequestMethod.GET)
    public JsonResult userinfo() {
        SellerUserInfo user_seller_infoModel = UserContext.getCurrentContext().getLoginInfo();
        if (user_seller_infoModel == null) {
            return JsonResult.get(HttpReturnRnums.NOT_LOGIN);
        }
        if (StringUtils.isEmpty(user_seller_infoModel.getHead_figure())) {
            user_seller_infoModel.setHead_figure(WebConfig.getImgUrl() + "base/no_icon.jpg");
        }
        int is_contract = t_projectService.getIsContract(user_seller_infoModel.getUser_id());
        user_seller_infoModel.setIs_contract(is_contract);
        return JsonResult.get(user_seller_infoModel);
    }

    @ApiOperation(value = "用户登出")
    @RequestMapping(value = "/marvel/logonout", method = RequestMethod.GET)
    public JsonResult logonout(HttpServletRequest request, HttpServletResponse response) {
        CookieUtils.deleteCookie(request, response, GlobalSettings.SELLER_COOKIENAME);
        return new JsonResult(HttpReturnRnums.Success);
    }

//    @ApiOperation(value = "用户激活")
//    @RequestMapping(value = "/nologon/marvel/activate", method = RequestMethod.POST)
//    public JsonResult activate(@RequestBody UserActivateReq req) {
//        return t_User_seller_infoService.activate(req);
//    }
//
//    @ApiOperation(value = "发起重置密码")
//    @RequestMapping(value = "/nologon/marvel/sendrestpasswd", method = RequestMethod.GET)
//    public JsonResult sendrestpasswd(UserSendRestPasswdReq req) {
//        return t_User_seller_infoService.sendRestPasswd(req);
//    }
//
//    @ApiOperation(value = "重置密码")
//    @RequestMapping(value = "/nologon/marvel/restpasswd", method = RequestMethod.POST)
//    public JsonResult restpasswd(@RequestBody UserRestPasswdReq req) {
//        return t_User_seller_infoService.restPasswd(req);
//    }

    @ApiOperation(value = "获取验证码")
    @RequestMapping(value = "/nologon/imgcode", method = RequestMethod.GET)
    public void imgCode(HttpServletRequest request,
                        HttpServletResponse response) {
        //注册1，找回密码2
//        String type_id = request.getParameter("type_id");

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-catch");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "image/jpeg");
        String sRand = RandomCodeStrGenerator.generateCode(4);
        BufferedImage image = RandomCodeImgHelper.getCodeImg(sRand);
        String cookie_name = GlobalSettings.SELLERIMGCode_COOKIE_NAME;
        CookieUtils.setCookie(request, response, cookie_name, AES.aesEncrypt(sRand), 5 * 60);
//        LoginHelper.storeAuthCode2Redis(sRand,
//                cookie_name, request, response);

        //输出图像到页面
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "JPEG", os);

            os.flush();
            os.close();
            os = null;
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Title 验证图片验证码是否正确
     * @author liupeng
     */
    @ApiOperation("验证图片验证码是否正确")
    @RequestMapping(value = "/nologon/checkimgcode", method = RequestMethod.GET)
    public JsonResult checkImgCode(HttpServletRequest request) {
        JsonResult js = new JsonResult();
        String img_code = request.getParameter("img_code");
        if (StringUtils.isEmpty(img_code)) {
            return new JsonResult(HttpReturnRnums.CHECK_CODE_ERROR);
        }
        String cookie_name = GlobalSettings.SELLERIMGCode_COOKIE_NAME;
        String value= CookieUtils.getCookie(request,cookie_name);
        String sessionCode= AES.aesDecrypt(value);
//        String sessionCode = LoginHelper.getAuthCode(request, cookie_name);
        if (sessionCode == null
                || !sessionCode.toString().toLowerCase()
                .equals(img_code.toLowerCase())) {
            return new JsonResult(HttpReturnRnums.CHECK_CODE_ERROR);
        }
        return js;
    }

}
